package leetcode.d_1_99;

// https://leetcode.cn/problems/string-to-integer-atoi/
// 字符串转数字
public class P8 {
    public int myAtoi(String s) {
        char[] chars = s.trim().toCharArray();
        if (chars.length == 0) {
            return 0;
        }
        int sign = 1;
        int i = 0;
        int res = 0;
        int bndry = Integer.MAX_VALUE /10;

        if (chars[0] == '-') {
            sign = -1;
            i=1;
        }
        if (chars[0] == '+') {
            i=1;
        }

        for (int j=i; j<chars.length; j++) {
            char ch = chars[j];
            if (ch < '0' || ch > '9') {
                break;
            }
            if (res > bndry || res == bndry && ch > '7') {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            res = res*10 + (ch - '0');
        }
        return sign * res;
    }
}
